# _*_ coding:utf-8 _*_
# @Time  : 2023.03.13
# @Author: zizlee
from typing import List
from fastapi import APIRouter, Header, Body
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from v1_all_api.all_response import AllResponse
from v1_all_api import constant

from db import FAConnection

notice_api = APIRouter()


class NoticeItem(BaseModel):
    notice_time: str
    exchange: str
    title: str
    href_url: str
    hash_key: str


@notice_api.post('/')  # 添加通知公告记录
def create_exchange_notice(user_agent: str = Header(...), notice_list: List[NoticeItem] = Body(...)):
    if user_agent != constant.DATA_WORKER_USER_AGENT:
        return AllResponse.forbidden_error()
    # 更新数据
    up_sql = "UPDATE dat_exchange_notice SET title=%(title)s,href_url=%(href_url)s WHERE hash_key=%(hash_key)s;"

    # 保存数据
    in_sql = """
        INSERT IGNORE INTO dat_exchange_notice (notice_time,exchange,title,href_url,hash_key) 
        VALUES (%(notice_time)s,%(exchange)s,%(title)s,%(href_url)s,%(hash_key)s);
    """
    notice_data = jsonable_encoder(notice_list)
    with FAConnection() as cursor:
        up_count = cursor.executemany(up_sql, notice_data)
        in_count = cursor.executemany(in_sql, notice_data)
    return AllResponse.operate_successfully(msg='更新条目{}个，新增条目{}个.'.format(up_count, in_count))
